package com.nongcai159.mall.lib_common.widgets

import android.content.Context
import android.support.v4.widget.SwipeRefreshLayout
import android.util.AttributeSet
import android.view.MotionEvent

import com.nongcai159.mall.lib_common.impl.ICanChildScrollUp

/**
 * Created by tanbiheng on 2017/10/13.
 */

class DefSwipeRefreshLayout : SwipeRefreshLayout {
    private var iCanChildScrollUp: ICanChildScrollUp? = null

    // 是否存在左右滑动事件
    private var mDragger: Boolean = false
    // 记录手指按下的位置
    private var mStartY = 0F
    private var mStartX = 0F
    // 出发事件的最短距离
    private val mTouchSlop = 0

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    fun setICanChildScrollUp(iCanChildScrollUp: ICanChildScrollUp) {
        this.iCanChildScrollUp = iCanChildScrollUp
    }

    override fun canChildScrollUp(): Boolean = iCanChildScrollUp?.canChildScrollUp()
            ?: super.canChildScrollUp()

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        val action = ev.action
        when (action) {
            MotionEvent.ACTION_DOWN -> {
                // 记录手指按下的位置
                mStartY = ev.y
                mStartX = ev.x
                //初始化左右滑动事件为false
                mDragger = false
            }
            MotionEvent.ACTION_MOVE -> {
                //如果左右滑动事件为true  直接返回false 不拦截事件
                if (mDragger) {
                    return false
                }

                // 获取当前手指位置
                val endY = ev.y
                val endX = ev.x
                //获取X,Y滑动距离的绝对值
                val distanceX = Math.abs(endX - mStartX)
                val distanceY = Math.abs(endY - mStartY)

                // 如果X轴位移大于Y轴距离，那么将事件交给其他控件
                if (distanceX > mTouchSlop && distanceX > distanceY) {
                    mDragger = true
                    return false
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL ->
                //初始化左右滑动事件为false
                mDragger = false
        }

        return super.onInterceptTouchEvent(ev)
    }
}
